package io.afu.validator.Implement;

import io.afu.validator.Annimation.IsUrl;
import io.afu.validator.Constant.CommonConstant;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Annotation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IsUrlValidatorImpl implements ConstraintValidator<IsUrl,String> {


    private Boolean allowEmpty;

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (null == s || "".equals(s)){
            return allowEmpty;
        }else {
            String patten = "(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\\\+&amp;%\\$#_]*)?";

            Pattern p = Pattern.compile(patten);
            Matcher m = p.matcher(s);
            return m.find();
        }
    }

    @Override
    public void initialize(IsUrl constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
    }
}
